//
//  SLLocatinViewController.m
//  StarLight
//
//  Created by Duke.wu on 16/5/13.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLLocatinViewController.h"
#import "SLLocationSearchManager.h"
#import "STPopup.h"

@interface SLLocatinViewController ()<QMapViewDelegate, UITableViewDelegate,QMSSearchDelegate,UISearchBarDelegate>

@property (nonatomic, strong) QMapView *qMapView;

@property (nonatomic, strong) QMSSearcher *qMapSearcher;

@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) SLLocationSearchManager *searchManager;

@property (nonatomic, strong) SLLocationSearchResultsManager *resultsManager;

@property (nonatomic, strong) QMSGeoCodeSearchResult *geoResult;

@property (nonatomic, strong) UITableView *suggestionTableView;

@property (nonatomic, strong) UITableView *aroundTableView;

@property (nonatomic, strong) UILabel *currentLocationLabel;

@property (nonatomic, strong) QMSPoiSearchOption *poiSearchOption;

@end

@implementation SLLocatinViewController


- (instancetype)init{
  if (self = [super init]) {
    self.contentSizeInPopup = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    self.landscapeContentSizeInPopup = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
  }
  return self;
}

- (void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  self.view.backgroundColor = [UIColor defeutBackgroudColor];
  [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
  [self.view addSubview:self.searchBar];
  [self.view addSubview:self.qMapView];
  [self.view addSubview:self.currentLocationLabel];
  [self.view addSubview:self.aroundTableView];
  [self.view addSubview:self.suggestionTableView];

  [self addConstrains];
}

- (void)addConstrains{
  [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.view);
    make.top.equalTo(self.view);
    make.right.equalTo(self.view);
    make.height.equalTo(@50);
  }];
  
  [self.qMapView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.searchBar.mas_bottom);
    make.left.width.equalTo(self.view);
    make.height.equalTo(self.view).multipliedBy(0.5);
    
  }];
  
  UIImageView *leftImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"currentLocation"]];
  [self.qMapView addSubview:leftImageView];
  [leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.center.equalTo(self.qMapView);
    make.size.mas_equalTo(CGSizeMake(16, 18));
  }];
  
  [self.currentLocationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.qMapView.mas_bottom);
    make.centerX.equalTo(self.view);
  }];
  
  [self.aroundTableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.currentLocationLabel.mas_bottom);
    make.left.width.equalTo(self.view);
    make.bottom.equalTo(self.view);
  }];
  
  
  
  
}


- (void)addObservers{
  
  
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)fetchGeoData:(QMSSuggestionPoiData *)suggestionPoiData{
  //配置搜索参数
  QMSGeoCodeSearchOption *geoOption = [[QMSGeoCodeSearchOption alloc] init];
  [geoOption setAddress:[suggestionPoiData address]];
  [geoOption setRegion:@"北京"];
  
  [self.qMapSearcher searchWithGeoCodeSearchOption:geoOption];
}

- (void)setupAnnotation{
  [self.qMapView removeAnnotations:self.qMapView.annotations];
  [self.qMapView setCenterCoordinate:self.geoResult.location];
  
  PoiAnnotation *annotation = [[PoiAnnotation alloc] initWithPoiData:self.geoResult];
  [annotation setCoordinate:self.geoResult.location];
  [annotation setTitle:[NSString stringWithFormat:@"%@%@", self.geoResult.address_components.city, self.geoResult.address_components.district]];
  [annotation setSubtitle:[NSString stringWithFormat:@"lat:%f, lng:%f", self.geoResult.location.latitude, self.geoResult.location.longitude]];
  [self.qMapView addAnnotation:annotation];
}



#pragma mark - MapDelegate

-(void)mapView:(QMapView *)mapView didUpdateUserLocation:(QUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
  if (userLocation != nil ) {
    [self.poiSearchOption setBoundaryByNearbyWithCenterCoordinate:userLocation.coordinate radius:1000];
    [self.qMapSearcher searchWithPoiSearchOption:self.poiSearchOption];
  }
}

- (void)mapView:(QMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
  
}

-(void)mapView:(QMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
  [self.poiSearchOption setBoundaryByNearbyWithCenterCoordinate:mapView.centerCoordinate
                                                         radius:1000];
  [self.qMapSearcher searchWithPoiSearchOption:self.poiSearchOption];
  [self.aroundTableView reloadData];
}


#pragma mark - QMSSearcher Delegate

- (void)searchWithSearchOption:(QMSSearchOption *)searchOption didFailWithError:(NSError *)error
{
  NSLog(@"error:%@", error);
}

- (void)searchWithSuggestionSearchOption:(QMSSuggestionSearchOption *)suggestionSearchOption didReceiveResult:(QMSSuggestionResult *)suggestionSearchResult
{
  self.searchManager.suggestionResut = suggestionSearchResult;
  [self.suggestionTableView reloadData];
}

- (void)searchWithGeoCodeSearchOption:(QMSGeoCodeSearchOption *)geoCodeSearchOption didReceiveResult:(QMSGeoCodeSearchResult *)geoCodeSearchResult
{
  self.geoResult = geoCodeSearchResult;
  [self setupAnnotation];
}

- (void)searchWithPoiSearchOption:(QMSPoiSearchOption *)poiSearchOption didReceiveResult:(QMSPoiSearchResult *)poiSearchResult{
  QMSSuggestionPoiData *poi = poiSearchResult.dataArray[0];
  self.currentLocationLabel.text = [NSString stringWithFormat:@"当前位置 :%@",poi.title];
  
  self.resultsManager.poiResults = poiSearchResult;
  [self.aroundTableView reloadData];
}



#pragma mark - SearchDisplayController Delegate

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
  [self searchCancel];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
  searchBar.showsCancelButton = YES;
  for(id cc in [searchBar subviews][0].subviews){
    if([cc isKindOfClass:[UIButton class]]){
      UIButton *sbtn = (UIButton *)cc;
      [sbtn setTitle:@"取消"  forState:UIControlStateNormal];
      [sbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
  }
  return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
  [self. suggestionTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
    make.left.right.bottom.equalTo(self.view);
    make.top.equalTo(self.searchBar.mas_bottom);
  }];
  [self.view layoutIfNeeded];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
  
  [self searchSuggestionsWithKeyWord:searchText];
}

- (void)searchSuggestionsWithKeyWord:(NSString *)keyWord{
  //配置搜索参数
  QMSSuggestionSearchOption *suggetionOption = [[QMSSuggestionSearchOption alloc] init];
  [suggetionOption setKeyword:keyWord];
  [suggetionOption setRegion:@"北京"];
  
  [self.qMapSearcher searchWithSuggestionSearchOption:suggetionOption];
}

- (void)searchCancel{
  [self.view endEditing:YES];
  self.searchBar.showsCancelButton = NO;
  [self.suggestionTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.searchBar.mas_bottom);
    make.height.equalTo(@0);
  }];
  [self.view layoutIfNeeded];
}


#pragma mark - Search Result Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (tableView.tag == 100) {
    [self fetchGeoData:[self.searchManager.suggestionResut.dataArray objectAtIndex:[indexPath row]]];
    [self searchCancel];
  }else{
    QMSPoiData *poi = [self.resultsManager.poiResults.dataArray objectAtIndex:indexPath.row];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeLocation" object:nil userInfo:@{@"location":poi}];

    [self.navigationController popViewControllerAnimated:YES];
    [self.popupController popViewControllerAnimated:YES];
  }
  
  
}



#pragma mark - getter

-(QMapView *)qMapView{
  if (!_qMapView) {
    _qMapView = [QMapView new];
    _qMapView.delegate = self;
    _qMapView.userTrackingMode = QUserTrackingModeFollow;

  }
  return _qMapView;
}

- (UILabel *)currentLocationLabel{
  if (!_currentLocationLabel) {
    _currentLocationLabel = [UILabel new];
    _currentLocationLabel.textColor = SLYellowColor;
  }
  return _currentLocationLabel;
}

- (QMSSearcher *)qMapSearcher{
  if(!_qMapSearcher){
    _qMapSearcher = [[QMSSearcher alloc] init];
    _qMapSearcher.delegate = self;
  }
  return _qMapSearcher;
}

- (UISearchBar *)searchBar{
  if (!_searchBar) {
    _searchBar = [UISearchBar new];
    _searchBar.delegate = self;
  }
  return _searchBar;
}

- (SLLocationSearchResultsManager *)resultsManager{
  if (!_resultsManager) {
    _resultsManager = [SLLocationSearchResultsManager new];
  }
  return _resultsManager;
}

- (SLLocationSearchManager *)searchManager{
  if (!_searchManager) {
    _searchManager = [[SLLocationSearchManager alloc] init];
  }
  return _searchManager;
}

- (UITableView *)suggestionTableView{
  if (!_suggestionTableView) {
    _suggestionTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_suggestionTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"SuggestionREUSE_ID"];
    _suggestionTableView.dataSource = self.searchManager;
    _suggestionTableView.tag = 100;
    _suggestionTableView.delegate = self;
  }
  return _suggestionTableView;
}

- (UITableView *)aroundTableView{
  if (!_aroundTableView) {
    _aroundTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_aroundTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"aroundREUSE_ID"];
    _aroundTableView.dataSource = self.resultsManager;
    _aroundTableView.delegate = self;
  }
  return _aroundTableView;
}

- (QMSPoiSearchOption *)poiSearchOption{
  if (!_poiSearchOption) {
    _poiSearchOption = [[QMSPoiSearchOption alloc] init];
    [_poiSearchOption setBoundaryByNearbyWithCenterCoordinate:self.qMapView.centerCoordinate radius:1000];
  }
  return _poiSearchOption;
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
